import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import { compression } from 'vite-plugin-compression2'
import { visualizer } from 'rollup-plugin-visualizer'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          isCustomElement(tag) {
            return tag.startsWith('swiper-')
          }
        }
      }
    }),
    vueDevTools(),
    AutoImport({
      resolvers: [ElementPlusResolver()]
    }),
    Components({
      resolvers: [ElementPlusResolver()]
    }),
    compression({
      threshold: 5120, // 压缩前最小文件大小
      compressionOptions: {
        verbose: true, // 默认即可
        disable: false, // 开启压缩(不禁用)，默认即可
        deleteOriginFile: false, // 删除源文件
        algorithm: 'gzip', // 压缩算法
        ext: '.gz' // 文件类型
      }
    }),
    visualizer({
      open: true, // 注意这里要设置为true，否则无效，如果存在本地服务端口，将在打包后自动展示
      gzipSize: true,
      filename: 'stats.html', //分析图生成的文件名
      brotliSize: true
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    proxy: {
      '/api': {
        target: 'http://124.221.74.149:8010',
        // target: 'http://localhost:8010',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
  build: {
    minify: 'terser',
    terserOptions: {
      compress: {
        // 删除 console
        drop_console: true,
        // 删除debug
        drop_debugger: true
      }
    },
    chunkSizeWarningLimit: 1024,
    rollupOptions: {
      output: {
        assetFileNames: (assetInfo) => {
          const imageExt = ['png', 'gif', 'jpg', 'jpeg']
          if (imageExt.some((v) => assetInfo.name?.endsWith(v))) {
            return 'image/[name]-[hash].[ext]'
          } else {
            return '[ext]/[name]-[hash].[ext]'
          }
        },
        chunkFileNames: 'js/[name]-[hash].js',
        entryFileNames: 'js/[name]-[hash].js'
      }
    }
  }
})
